import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net'
//请求拦截器
http.intercept.request = function (options) {
  const defaultHeader = {}
  defaultHeader.Authorization = 'Bearer ' + getApp().token
  options.header = Object.assign({}, defaultHeader, options.header)
  return options
}
//响应拦截器
http.intercept.response = async function ({ data, config }) {
  if (data.code === 401) {
    console.log('你好')
    //判断refreshtoken是否过期
    if (config.url.includes('/refreshToken')) {
      const pageStack = getCurrentPages()
      const currentPage = pageStack.pop()
      const redirectURL = currentPage.route
      // 跳由跳转（登录页面）
      return wx.redirectTo({
        url: '/pages/login/index?redirectURL=/' + redirectURL,
      })
    }
    //利用refreshtoken获取新token
    const app = getApp()

    const res = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: 'Bearer ' + app.refreshToken,
      },
    })
    if (res.code !== 10000) return wx.utils.toast('更新用户token失败')
    app.setToken('token', res.data.token)
    app.setToken('refreshToken', res.data.refreshToken)

    config = Object.assign(config, {
      header: {
        Authorization: 'Bearer ' + res.data.token,
      },
    })
    return http(config)
  }

  return data
}
export default http

wx.http = http
